﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

using SmlEngine.UI.Managers;

namespace SmlEngine.UI.Screens
{
    public class ScreenGroup
    {
        #region Properties and Fields
        public List<Screen> Screens = new List<Screen>();

        private bool isInitialized;
        private bool isContentLoaded;

        private ScreenManager owner;

        public int Count
        {
            get
            {
                return Screens.Count;
            }
        }

        /// <summary>
        /// Returns the zero-based length of the screens stored in this group.
        /// </summary>
        public int Length
        {
            get
            {
                return Screens.Count - 1;
            }
        }

        public Screen this[int index]
        {
            get
            {
                return Screens[index];
            }
        }
        #endregion

        #region Methods

        #region Constructors
        public ScreenGroup(ScreenManager _owner, params Screen[] screens)
        {
            Screens = screens.ToList<Screen>();
            owner = _owner;
        }
        #endregion

        #region Initializing and Loading
        public void Initialize()
        {
            if (!isInitialized)
            {
                Screens.ForEach(s => s.Initialize());
                isInitialized = true;
            }
        }

        public void LoadContent(ContentManager Content)
        {
            if (!isContentLoaded)
            {
                Screens.ForEach(s => s.LoadContent(Content));
                isContentLoaded = true;
            }
        }

        public void UnloadContent()
        {
            if (isContentLoaded)
            {
                Screens.ForEach(s => s.UnloadContent());
                isContentLoaded = false;
            }
        }

        public int AddScreen(Screen screen)
        {
            screen.ScreenManager = owner;
            screen.IsExiting = false;
            if (isInitialized)
                screen.Initialize();
            if (isContentLoaded)
                screen.LoadContent(owner.Game.Content);
            Screens.Add(screen);
            return Screens.IndexOf(screen);
        }

        public void RemoveScreen(Screen screen)
        {
            if (isContentLoaded)
                screen.UnloadContent();

            Screens.Remove(screen);
        }

        public void RemoveAllScreens()
        {
            Screens.ForEach(s => s.UnloadContent());
            Screens.Clear();
            isInitialized = false;
            isContentLoaded = false;
        }
        #endregion

        #endregion
    }
}
